package com.inspinia.message.rpc.service;

import cn.hutool.core.collection.CollectionUtil;
import com.inspinia.base.dao.BaseDao;
import com.inspinia.base.service.BaseServiceImpl;
import com.inspinia.message.common.model.NoticeAddressee;
import com.inspinia.message.common.model.NoticeAddresseeType;
import com.inspinia.message.dao.NoticeAddresseeDao;
import com.inspinia.message.rpc.api.NoticeAddresseeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 通知收件人的服务层实现类
 * Created by heshun on 2018-1-8.
 */
@Service
public class NoticeAddresseeServiceImpl extends BaseServiceImpl<NoticeAddressee> implements NoticeAddresseeService {
    @Resource
    private NoticeAddresseeDao noticeAddresseeDao;

    @Override
    protected BaseDao<NoticeAddressee> getDao() {
        return noticeAddresseeDao;
    }


    @Override
    @Transactional
    public List<Long> batchInsert(Long noticeId, NoticeAddresseeType addresseeType, Collection<Long> addresseeIds) {

        List<NoticeAddressee> beans = new ArrayList<>();
        if (NoticeAddresseeType.all == addresseeType) {
            beans.add(new NoticeAddressee(noticeId, addresseeType, null, false));
        } else if (CollectionUtil.isNotEmpty(addresseeIds)) {
            for (Long addresseeId : addresseeIds) {
                beans.add(new NoticeAddressee(noticeId, addresseeType, addresseeId, false));
            }
        }

        if (CollectionUtil.isNotEmpty(beans)) {
            noticeAddresseeDao.batchInsert(beans);
            List<Long> ids = new ArrayList<>();
            beans.forEach(b -> ids.add(b.getId()));
            return ids;
        }
        return Collections.EMPTY_LIST;
    }

    @Override
    @Transactional
    public int setPushed(List<Long> ids) {
        return noticeAddresseeDao.setPushed(ids);
    }

    @Override
    public List<NoticeAddressee> findUnPushed(Long noticeId) {
        return noticeAddresseeDao.findUnPushed(noticeId);
    }

    @Override
    public void deleteDayBefore(int day) {
        noticeAddresseeDao.deleteDayBefore(day);
    }

}

